import 'dart:convert';
import 'dart:ui';
import 'package:base_lib/common/base/base_bloc_page.dart';
import 'package:base_lib/index.dart';
import 'package:base_lib/router/parameters.dart';
import 'package:base_lib/theme/theme_global.dart';
import 'package:doctor_prescribe_lib/chinese_medicine/medicine_search/page.dart';
import 'package:doctor_prescribe_lib/doctor_prescribe_component.dart';
import 'package:doctor_prescribe_lib/offline/basic_info/bloc.dart';
import 'package:doctor_prescribe_lib/repository/http.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:common_lib/patient_management/patient_list/patient_list_entity.dart'
    as PatientBean;
import 'package:doctor_prescribe_lib/western_medicine/medical_search/entity/medical_search_entity.dart'
    as MedicineSearchBean;
import '../../prescribe_util.dart';
import 'bloc.dart';

///处方开立页
class ChinesePrescriptionPage extends BaseBlocPage<ChinesePrescriptionPageBloc,
    _ChinesePrescriptionPageState> {
  ChinesePrescriptionPage(Parameters parameters) : super(parameters);

  @override
  _ChinesePrescriptionPageState generateThemeState() {
    return _ChinesePrescriptionPageState();
  }
}

class _ChinesePrescriptionPageState
    extends BaseBlocPageState<ChinesePrescriptionPageBloc> {
  @override
  void initState() {
    super.initState();
  }

  bool isLoading = false;

  var tsBlack = TextStyle(color: Colors.black);

  String direction = '内服';

  String enjoin = '';

  int totalDoses = 1;
  int frequency = 1;
  int everyDose = 1;

  @override
  Widget buildChild(BuildContext context, MTheme theme) {
    return Scaffold(
      appBar: AppBar(
        leading: BackButton(
          onPressed: () {
            Routers.pop(context);
          },
        ),
        centerTitle: true,
        title: Text('处方开立页'),
      ),
      body: Container(
        alignment: Alignment.topCenter,
        height: double.infinity,
        color: Colors.grey[200],
        child: SingleChildScrollView(
          physics: BouncingScrollPhysics(),
          child: LayoutBuilder(
            builder: (context, constraints) {
              return Container(
                constraints: constraints,
                child: Column(
                  children: [
                    Container(
                      width: double.infinity,
                      decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(10)),
                      margin: EdgeInsets.all(20),
                      padding: EdgeInsets.all(10),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text('R:',
                              style: tsBlack.copyWith(
                                  fontSize: 20, fontWeight: FontWeight.bold)),
                          _buildMedicines(theme),
                          10.vGapDp,
                          GestureDetector(
                            onTap: () {
                              jump2MedicalEdit();
                            },
                            child: Row(
                              children: [
                                Icon(
                                  Icons.edit,
                                  color: theme.themeColor.themeColor,
                                  size: 15,
                                ),
                                Text(
                                  '编辑用药',
                                  style: tsBlack.copyWith(
                                      color: theme.themeColor.themeColor),
                                )
                              ],
                            ),
                          ),
                          10.vGapDp,
                          DottedLine(color: Colors.grey[300], dashWidth: 3),
                          10.vGapDp,
                          Row(
                            children: [
                              Text(
                                '用法用量',
                                style: tsBlack.copyWith(
                                    fontSize: 16, fontWeight: FontWeight.bold),
                              ),
                              Spacer(),
                              Radio(
                                  value: '内服',
                                  groupValue: direction,
                                  onChanged: (value) {
                                    direction = value;
                                    doRefresh();
                                  }),
                              Text(
                                '内服',
                                style: tsBlack,
                              ),
                              5.hGapDp,
                              Radio(
                                  value: '外用',
                                  groupValue: direction,
                                  onChanged: (value) {
                                    direction = value;
                                    doRefresh();
                                  }),
                              Text(
                                '外用',
                                style: tsBlack,
                              ),
                            ],
                          ),
                          10.vGapDp,
                          DefaultTextStyle(
                            style: tsBlack,
                            child: Wrap(
                              children: [
                                Text('共'),
                                SizedBox(
                                  width: ScreenAdapter.screenWidthDp / 12,
                                  height: 20,
                                  child: TextField(
                                    controller: TextEditingController(
                                        text: totalDoses.toString()),
                                    textAlign: TextAlign.center,
                                    keyboardType: TextInputType.number,
                                    maxLines: 1,
                                    onChanged: (str) {
                                      if (str.isEmpty) return;
                                      try {
                                        totalDoses = int.parse(str);
                                      } catch (e) {
                                        print(e);
                                        ToastUtil.error('请输入正确的数量');
                                      }
                                    },
                                    onSubmitted: (str) {
                                      doRefresh();
                                    },
                                  ),
                                ),
                                Text('剂，'),
                                Text('每日'),
                                SizedBox(
                                  width: ScreenAdapter.screenWidthDp / 12,
                                  height: 20,
                                  child: TextField(
                                    controller: TextEditingController(
                                        text: frequency.toString()),
                                    textAlign: TextAlign.center,
                                    keyboardType: TextInputType.number,
                                    maxLines: 1,
                                    onChanged: (str) {
                                      if (str.isEmpty) return;
                                      try {
                                        frequency = int.parse(str);
                                      } catch (e) {
                                        print(e);
                                        ToastUtil.error('请输入正确的数量');
                                      }
                                    },
                                  ),
                                ),
                                Text('剂，'),
                                Text('每剂分'),
                                SizedBox(
                                  width: ScreenAdapter.screenWidthDp / 12,
                                  height: 20,
                                  child: TextField(
                                    controller: TextEditingController(
                                        text: everyDose.toString()),
                                    style: tsBlack.copyWith(color: Colors.red),
                                    decoration: InputDecoration(
                                        focusedBorder: UnderlineInputBorder(
                                            borderSide:
                                                BorderSide(color: Colors.red))),
                                    textAlign: TextAlign.center,
                                    keyboardType: TextInputType.number,
                                    maxLines: 1,
                                    onChanged: (str) {
                                      if (str.isEmpty) return;
                                      try {
                                        everyDose = int.parse(str);
                                      } catch (e) {
                                        print(e);
                                        ToastUtil.error('请输入正确的数量');
                                      }
                                    },
                                  ),
                                ),
                                Text('次使用'),
                              ],
                            ),
                          ),
                          20.vGapDp,
                          Text(
                            '共：¥${PrescribeUtil.formatMoney(totalPrice())}',
                            style: tsBlack.copyWith(color: Colors.red),
                          ),
                          10.vGapDp,
                          DottedLine(color: Colors.grey[300], dashWidth: 3),
                          10.vGapDp,
                          Text(
                            '医嘱提醒',
                            style: tsBlack.copyWith(
                                fontSize: 16, fontWeight: FontWeight.bold),
                          ),
                          10.vGapDp,
                          Container(
                            padding: EdgeInsets.all(10),
                            decoration: BoxDecoration(
                                color: Colors.grey[200],
                                borderRadius: BorderRadius.circular(10)),
                            child: TextField(
                              controller: TextEditingController(text: enjoin),
                              maxLines: 4,
                              maxLength: 100,
                              keyboardType: TextInputType.text,
                              textAlign: TextAlign.start,
                              style: tsBlack,
                              decoration: InputDecoration(
                                  border: InputBorder.none,
                                  hintStyle:
                                      tsBlack.copyWith(color: Colors.grey),
                                  hintText: '请在这里输入医嘱...'),
                              onChanged: (str) {
                                enjoin = str;
                              },
                            ),
                          ),
                          10.vGapDp,
                        ],
                      ),
                    ),
                    25.vGapDp,
                    isLoading
                        ? buildLoadingIndicator()
                        : GestureDetector(
                            onTap: () {
                              doNext();
                            },
                            child: Container(
                              alignment: Alignment.center,
                              height: 45,
                              width: double.infinity,
                              margin: EdgeInsets.symmetric(
                                  horizontal: 25, vertical: 30),
                              decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(20),
                                  color: theme.themeColor.themeColor),
                              child: Text(
                                '下一步',
                                style: tsBlack.copyWith(color: Colors.white),
                              ),
                            ),
                          ),
                    30.vGapDp,
                  ],
                ),
              );
            },
          ),
        ),
      ),
    );
  }

  @override
  ChinesePrescriptionPageBloc generateBloc() {
    return ChinesePrescriptionPageBloc();
  }

  _buildMedicines(MTheme theme) {
    var widgets = <Widget>[];

    ChinesePrescriptionPageBloc.rxMedicineList.forEach((element) {
      widgets.add(5.vGapDp);
      var w = Text(
        '${element.medicineName}   ${element.medicineAmount}g   (${element.usage})',
        style: tsBlack,
      );
      widgets.add(w);
    });

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: widgets,
    );
  }

  void jump2MedicalEdit() {
    Routers.navigateTo(context, DoctorPrescribeComponent.chineseMedicalEditPage,
            parameters: Parameters()
              ..putString('orgID', bloc.doctorUser.orgID)
              ..putInt('orgTypeID', bloc.doctorUser.orgTypeID))
        .then((value) {
      doRefresh();
    });
  }

  double totalPrice() {
    if (totalDoses < 1) {
      return 0;
    } else {
      var amount = 0.0;
      ChinesePrescriptionPageBloc.rxMedicineList.forEach((element) {
        amount += element.price;
      });
      return amount * totalDoses;
    }
  }

  void doNext() async {
    if (totalDoses < 1 || totalDoses > 100) {
      ToastUtil.warning("剂量填写错误！");
      return;
    } else if (frequency < 1 || frequency > 100) {
      ToastUtil.warning("服用次数填写错误！");
      return;
    } else if (ChinesePrescriptionPageBloc.rxMedicineList.isEmpty) {
      ToastUtil.warning("请先添加处方药！");
      return;
    }

    var offRp = bloc.basicInfoData.offlineRpEntity;
    offRp.rp
          ..totalDoses = this.totalDoses
          ..enjoin = this.enjoin
          ..chineseMedicine.frequence = this.frequency
          ..chineseMedicine.direction = this.direction
          ..chineseMedicine.everyDose = this.everyDose
        // ..providerType = 1
        ;

    var amount = totalPrice();

    offRp.rp.recipeAllPrice = amount;
    offRp.rpMedicines = ChinesePrescriptionPageBloc.rxMedicineList;

    isLoading = true;
    doRefresh();
    var result = await PrescribeHttp.postOfflineRp(json.encode(offRp));
    if (result.isSuccess) {
      //    this.rpID = res.rpID;
      //             // 跳往订单详情
      //             navigator.push({
      //               url: "js://underPrescription/RpOrder.js",
      //               extra: {
      //                 talkInfo: this.talkInfo,
      //                 rpID: this.rpID,
      //                 doctorID: this.userInfo.keyID
      //               }
      //             });

      Routers.navigateTo(context, DoctorPrescribeComponent.rpOrderPage,
          parameters: Parameters()..putString('rpID', result.data));
    } else {
      ToastUtil.error(result.error.msg);
    }
    isLoading = false;
    doRefresh();
  }

  doRefresh() {
    setState(() {});
  }
}
